19. 删除链表的倒数第 N 个结点

19. 删除链表的倒数第 N 个结点

Similar Question

leading to the advanced question

Solution Tips

处理倒数的问题, 可以使用快慢指针

处理 length - n 的问题可以使用快慢指针

方案一: 遍历

linked-list

方案二: 快慢指针

p9oCA2V.png

p9oCuVJ.png

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode first = head;
        ListNode second = dummy;
        for (int i = 0; i < n; ++i) {
            first = first.next;
        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        ListNode ans = dummy.next;
        return ans;
    }
}